const UPPER_ATACK_PER_LEVEL = 10;
const UPPER_MAXHP_PER_LEVEL = 100;


/**
 * 用户数据
 * MVC：Model
 */
class User extends EventDispatcher {


    private path: { x: number, y: number }[] = [];

    view: renderer.DisplayObject;

    walkSpeed = 4;

    constructor() {
        super();
        const roleTexture = new Image();
        roleTexture.src = 'piqiu.png';
        const role = new renderer.Bitmap(0, 0, roleTexture);
        this.view = role;
    }


    update() {
        if (this.path.length > 0) {

            const nextNode = this.path[0]

            const targetX = nextNode.x * TILE_SIZE;
            const targetY = nextNode.y * TILE_SIZE;

            const diffX = targetX - this.view.x;
            const diffY = targetY - this.view.y;
            const speedX = normalize(diffX, this.walkSpeed);
            const speedY = normalize(diffY, this.walkSpeed);



            if (speedX == 0 && speedY == 0) {

                const map = mapManager.getMap();

                map.grid.setStartNode(nextNode.x, nextNode.y)
                console.log("x:" + nextNode.x + "  y:" + nextNode.y);




                //TODO:站立动画
                this.path.shift();
                if (this.path.length == 0) {
                    this.dispatchEvent("goOver", null);
                }

            }
            else {
                this.dispatchEvent("",null)//移动动画
            }

            this.view.x += speedX;
            this.view.y += speedY;

        }
    }

    goto(path: { x: number, y: number }[]) {
        this.path = path;
    }


    name: string = '';

    hp: number = 100;

    sliverCoin = 0;

    get maxHp() {
        return this.level * UPPER_MAXHP_PER_LEVEL;
    }


    private _level = 1;
    get level() {
        return this._level;
    }

    set level(value: number) {
        this._level = value;
        this.dispatchEvent("userchange", "111");
    }

    pick(item: Item) {
        this.mountedItems.push(item);
        console.log(`捡起${item.toString()}`);
        this.dispatchEvent("userchange", '111');
    }

    mountedItems: Item[] = [];

    packagedItems: Item[] = [];



    get attack() {
        let itemAttack = 0;
        for (let item of this.mountedItems) {
            itemAttack += item.attack
        }
        return this.level * UPPER_ATACK_PER_LEVEL + itemAttack;
    }

    toString() {
        return `[User: level:${this.level} , attack:${this.attack} , ${this.mountedItems.map((item) => item.toString())}]`
    }
}

class Item {

    attack: number = 10;

    name = "";

    y = 0;

    x = 0;





    view: renderer.DisplayObject;

    toString() {
        return `[Item: name:${this.name} attack:${this.attack}]`
    }
}



function normalize(a: number, value: number) {
    if (a == 0) {
        return 0;
    }
    else if (a > 0) {
        return value;
    }
    else {
        return -value;
    }
}



